import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import Icon from '../Icon'
import styles from './index.module.scss'

/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
type Props = {
    className?:   string
    src: string
    alt?: string
}

const Image = ({ className, src, alt }: Props) => {
    const imgRef = useRef<HTMLImageElement>(null)

    // 控制是否在加载中
    const [loading, setLoading] = useState(true)

    // 控制是否加载错误
    const [error, setError] = useState(false)

    // 加载成功
    const onLoad = () => {
        setError(false)
        setLoading(false)
    }

    // 加载失败
    const onError = () =>{
        setLoading(false)
        setError(true)
    }

    useEffect(() => {
        // 监听图片
        const current = imgRef.current!
        const observer = new IntersectionObserver(([{ isIntersecting }]) => {
            if (isIntersecting) {
                // 图片在可视区
                current.src = current.dataset.src!
                // 取消监听
                observer.unobserve(current)
            }
        })
        observer.observe(current)
    }, [])

  return (
    <div className={classnames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}
        {loading && (
            <div className="image-icon">
                <Icon type="iconphoto" />
            </div>
        )}
        
      {/* 加载出错时显示的内容 */}
      
       {error && (
            <div className="image-icon">
                <Icon type="iconphoto-fail" />
            </div>
       )}
      

      {/* 加载成功时显示的内容 */}
      
        {!error && (
            <img 
                alt={alt}
                data-src={src}
                ref={imgRef}
                onLoad={onLoad}
                onError={onError}
            />
        )}
      
    </div>
  )
}

export default Image
